package org.monk.phishphans2;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;

/**
 * @author Emery
 * 
 */
public class PhishPhans2Server {

	private static final String PROTOCOL = "https://";
	private static final String DOMAIN = "api.phish.net/";
	private static final String ENDPOINT = "api.js";
	private static final String BASEURI = PROTOCOL + DOMAIN + ENDPOINT;
	private static final String KEY = "99FE56B60047C9359582";
	private static final String FORMAT = "json";
	private Context context;

	public PhishPhans2Server(Context applicationContext) {
		this.context = applicationContext;	
	}

	
	/**
	 * 
	 * @param version
	 * @param method
	 * @param args
	 * @param userAgent
	 * @return Response
	 * @throws IOException
	 */
	public String fetch(String version, String method, String args,
			String userAgent) throws IOException {

		
		DefaultHttpClient client = new MyHttpClient(context);
		
		String uri = BASEURI + "?api=" + version + "&method=" + method
				+ "&format=" + FORMAT + "&apikey=" + KEY + args;

		// Log.i("PhishPhans URI:",uri);

		HttpPost post = new HttpPost(uri);
		HttpResponse getResponse = client.execute(post);
		HttpEntity responseEntity = getResponse.getEntity();
		
//		InputStream responseStream = client.execute(post).getEntity()
//				.getContent();
//
//		final char[] buffer = new char[0x10000];
//		StringBuilder out = new StringBuilder();
//		Reader in = new InputStreamReader(responseStream, "UTF-8");
//		int read;
//		do {
//			read = in.read(buffer, 0, buffer.length);
//			if (read > 0) {
//				out.append(buffer, 0, read);
//			}
//		} while (read >= 0);
//
//		return out.toString();
		return responseEntity.toString();
	}

}
